package com.yzmoney.wechat.action;

import com.yzmoney.common.action.BaseAction;
import com.yzmoney.common.model.JsonResult;
import com.yzmoney.wechat.model.general.WechatJsSDKConfig;
import com.yzmoney.wechat.service.WechatJsTokenService;
import com.yzmoney.wechat.util.WechatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 获取微信jsApi
 * <p/>
 * 参数：传递当前页面的url去除#号
 */
@Controller
public class JsConfigAction extends BaseAction {
    private static final Log log = LogFactory.getLog(JsConfigAction.class);

    @Resource
    private WechatJsTokenService wechatJsTokenService;

    @RequestMapping("/gzh/jsconfig")
    public String jsconfig(HttpServletRequest request, HttpSession session, ModelMap modelMap, String url) {
        String jsToken = wechatJsTokenService.getJsToken();
        String configUrl = !StringUtils.isBlank(url) ? url : "http://m.yzmoney.com/";
        int bashIndex = configUrl.indexOf("#");
        configUrl = bashIndex != -1 ? configUrl.substring(bashIndex) : configUrl;
        WechatJsSDKConfig jsSDKConfig = WechatUtils.getJsSDKConfig(jsToken, configUrl);
        modelMap.addAttribute("jsConfig", jsSDKConfig);
        return "/wechat/jsconfig";
    }

    @RequestMapping("/gzh/jsconfigjson")
    @ResponseBody
    public JsonResult jsconfigjson(HttpServletRequest request, HttpSession session, ModelMap modelMap, String url) {
        JsonResult jsonResult = new JsonResult();
        String jsToken = wechatJsTokenService.getJsToken();
        String configUrl = !StringUtils.isBlank(url) ? url : "http://m.yzmoney.com/";
        int bashIndex = configUrl.indexOf("#");
        configUrl = bashIndex != -1 ? configUrl.substring(bashIndex) : configUrl;
        WechatJsSDKConfig jsSDKConfig = WechatUtils.getJsSDKConfig(jsToken, configUrl);
        jsonResult.setData(jsSDKConfig);
        return jsonResult;
    }

}